import Axios from 'axios';
import store from '../store'
import {getToken, removeToken} from "./token";
import {Message, MessageBox} from "element-ui";
import router from "../router";

const instance = Axios.create({
    baseURL:'http://127.0.0.1:8088/',
    timeout:5000
});

instance.interceptors.request.use(
    config =>{
        config.withCredentials = true; //设置允许携带session
        if (store.getters.token){
            config.headers['token'] = getToken()
        }
        return config;
    },
        error => {
        return Promise.reject(error)
    }
)

instance.interceptors.response.use(
    response => {
        const res = response.data;
        if(res.data.errorCode === 20003){
            MessageBox.confirm('你的账号在别处登陆，请重新登陆', '安全提醒', {
                confirmButtonText: '重新登陆',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(()  =>{
                location.reload()
                removeToken();
            });
        }
        if (res.data.errorCode === 20004){
            MessageBox.confirm(res.data.errorMsg,'安全提醒',{
                confirmButtonText: '重新登陆',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() =>{
                removeToken();
                location.reload()
            })
        }
        if (res.data.errorCode === 40001){
            MessageBox.confirm(res.data.errorMsg,'安全提醒',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() =>{

            })
        }
        else {
            return res;
        }
    },
    error => {
        return Promise.reject(error);
    }
)

export default instance